package com.kerry.configure;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;

@Configuration
@ComponentScan(basePackages="com.kerry.service")
public class TransactionConfigure{
	
	@Bean
	public DataSourceTransactionManager transactionManager( DataSource dataSource) {
		//log.info("TransactionManager initd");
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean
	public TransactionInterceptor transactionInterceptor( DataSourceTransactionManager dataSourceTransactionManager) {
		//log.info("TransactionInterceptor 初始化");
		TransactionInterceptor ti = new TransactionInterceptor();
		ti.setTransactionManager(dataSourceTransactionManager);
		Properties properties = new Properties();
		properties.setProperty("get*", "PROPAGATION_REQUIRED,readOnly");
		properties.setProperty("insert*", "PROPAGATION_REQUIRED");
		properties.setProperty("delete*", "PROPAGATION_REQUIRED");
		properties.setProperty("update*", "PROPAGATION_REQUIRED");
//		properties.setProperty("*", "PROPAGATION_REQUIRED,readOnly");
		ti.setTransactionAttributes(properties);
		return ti;
	}

	@Bean
	public BeanNameAutoProxyCreator transactionAutoProxy() {
		//log.info("TransactionAutoProxy 初始化");
		BeanNameAutoProxyCreator transactionAutoProxy = new BeanNameAutoProxyCreator();
		// 使用jdk接口代理，不使用cglib代理
		transactionAutoProxy.setProxyTargetClass(true);
		transactionAutoProxy.setBeanNames(new String[] { "*ServiceImpl" });
		transactionAutoProxy.setInterceptorNames(new String[] { "transactionInterceptor" });
		return transactionAutoProxy;
	}

}
